<template>
  <div class="app-container">
    <el-card>
      <!-- 筛选条件区域 -->
      <div class="filter-container">
        <el-form :model="listQuery" label-width="auto">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="12" :lg="6">
              <el-form-item label="账号或姓名">
                <el-input v-model.trim="listQuery.name" @input.native="filterPercentChar" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="6">
              <el-form-item label-width="0">
                <el-button type="primary" @click="handleFilter">查询</el-button>
                <el-button @click="resetList">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 按钮区域 -->
      <div class="btn-container">
        <el-button type="primary" icon="el-icon-plus" @click="handleCreate">添加</el-button>
      </div>

      <!-- 表格区域 -->
      <el-table :data="list" border highlight-current-row :stripe="true">
        <el-table-column label="#" width="60">
          <template slot-scope="{ $index }">
            <span>
              {{ $index + (listQuery.page - 1) * listQuery.limit + 1 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" prop="name" :show-overflow-tooltip="true" />
        <el-table-column label="账号" prop="username" :show-overflow-tooltip="true" />
        <el-table-column label="性别" width="60">
          <template slot-scope="{ row }">{{ row.sex | sexFilter }}</template>
        </el-table-column>
        <el-table-column label="描述" prop="description" :show-overflow-tooltip="true" />
        <el-table-column label="更新时间" width="170">
          <template slot-scope="{ row }">
            <span v-if="row.updateTime">{{ row.updateTime }}</span>
            <span v-else>{{ row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="{ row }">
            <el-button type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </el-card>

    <!-- 添加/编辑 对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" @close="resetForm('dataForm')">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px">
        <el-form-item label="账号" prop="username">
          <el-input v-model.trim="temp.username" placeholder="由字母、数字、下划线组成，以字母开头，长度为5-16位" />
        </el-form-item>
        <el-form-item :class="dialogStatus === 'create' ? 'is-required' : ''" label="密码" prop="password">
          <el-input v-model.trim="temp.password" placeholder="由字母、数字、下划线组成，以字母开头，长度为6-18位" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model.trim="temp.name" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="temp.sex">
            <el-radio label="1">男</el-radio>
            <el-radio label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model.trim="temp.mobile" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model.trim="temp.email" />
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker v-model="temp.birthday" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item label="所属部门">
          <el-cascader v-model="selectedKeys1" :options="departmentList" :props="cascaderProps1" clearable filterable @change="departmentChanged" />
        </el-form-item>
        <el-form-item label="角色">
          <el-cascader v-model="selectedKeys2" :options="roleList" :props="cascaderProps2" clearable filterable @change="roleChanged" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model.trim="temp.description" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData('dataForm') : updateData('dataForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { userList, addUser, getUserDetail, updateUser, deleteUser } from '@/api/base/user' // 用户模块接口
import { fetchTree } from '@/api/base/group' // 角色 部门 接口
import Pagination from '@/components/Pagination' // 分页组件
import { addLevel, getTreeDeepArr } from '@/utils' // addLevel过滤角色和部门数据 getTreeDeepArr获取联级选择器的选中值
import { validUsername, validPhone, isPassWord } from '@/utils/validate'
export default {
  name: 'User',
  components: { Pagination },
  data() {
    const requirePassword = (rule, value, callback) => {
      if (value) {
        if (isPassWord(value)) {
          callback()
        } else {
          return callback(new Error('密码由字母、数字、下划线组成，以字母开头，长度为6-18位'))
        }
      } else {
        if (this.dialogStatus === 'create') {
          // 添加时必填
          return callback(new Error('请输入密码'))
        } else {
          // 编辑时非必填
          callback()
        }
      }
    }
    return {
      list: [], // 列表数据
      total: 0, // 列表总数
      listQuery: {
        // 列表查询参数
        page: 1,
        limit: 10,
        name: undefined
      },
      temp: {
        // 添加和编辑的提交数据
        username: undefined,
        password: 'Aa123456',
        name: undefined,
        sex: '1',
        mobile: undefined,
        email: undefined,
        birthday: undefined,
        org: null,
        role: null,
        description: undefined
      },
      dialogFormVisible: false, // 控制对话框显示或隐藏
      dialogStatus: '', // 对话框状态 'create'和'update'
      textMap: {
        // 对话框标题
        update: '编辑',
        create: '添加'
      },
      rules: {
        // 表单的验证规则
        username: [{ required: true, validator: validUsername, trigger: 'blur' }],
        password: [{ validator: requirePassword, trigger: 'blur' }],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { max: 10, message: '长度不能超过10位', trigger: 'blur' }
        ],
        mobile: [{ validator: validPhone, trigger: 'blur' }],
        email: [{ type: 'email', message: '请输入正确的邮箱', trigger: 'blur' }],
        description: [{ max: 500, message: '长度不能超过200位', trigger: 'blur' }]
      },
      departmentList: [], // 部门列表数据
      cascaderProps1: {
        // 部门选择器配置
        value: 'id',
        label: 'name',
        children: 'children',
        checkStrictly: true
      },
      selectedKeys1: [], // 部门选中值
      roleList: [], // 角色列表数据
      cascaderProps2: {
        // 角色选择器配置
        value: 'id',
        label: 'name',
        children: 'children',
        checkStrictly: true
      },
      selectedKeys2: [] // 角色选中值
    }
  },
  created() {
    // 组件创建完成
    this.getList()
    this.getDepartment()
    this.getRole()
  },
  methods: {
    async getList() {
      // 获取用户列表
      try {
        const {
          data: { records, total }
        } = await userList(this.listQuery)
        this.list = records
        this.total = total
      } catch (error) {
        console.log(error)
      }
    },
    handleFilter() {
      // 查询
      this.listQuery.page = 1
      this.getList()
    },
    resetList() {
      // 重置
      this.listQuery = {
        page: 1,
        limit: 10,
        name: undefined
      }
      this.getList()
    },
    handleCreate() {
      // 点击添加按钮
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    createData(formName) {
      // 添加
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            await addUser(this.temp)
            this.dialogFormVisible = false
            this.$message({
              message: '添加成功',
              type: 'success'
            })
            this.getList()
          } catch (error) {
            console.log(error)
          }
        }
      })
    },
    async handleUpdate(row) {
      // 点击编辑按钮
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      const { data } = await getUserDetail(row.id)
      this.temp = data
      this.selectedKeys1 = getTreeDeepArr(data.orgId, this.departmentList)
      this.selectedKeys2 = getTreeDeepArr(data.roleId, this.roleList)
      this.temp.org = data.orgId ? { id: data.orgId, groupType: 1 } : null
      this.temp.role = data.roleId ? { id: data.roleId, groupType: 1 } : null
    },
    updateData(formName) {
      // 更新
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            const { message } = await updateUser(this.temp)
            this.dialogFormVisible = false
            this.$message({
              message: message,
              type: 'success'
            })
            this.getList()
          } catch (error) {
            console.log(error)
          }
        }
      })
    },
    handleDelete(row) {
      // 点击删除按钮
      this.$confirm('此操作将删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { message } = await deleteUser(row.id)
          this.$message({
            type: 'success',
            message: message
          })
          this.getList()
        })
        .catch(() => {})
    },
    resetForm(formName) {
      // 对话框关闭时重置表单
      this.selectedKeys1 = []
      this.selectedKeys2 = []
      this.temp = {
        username: undefined,
        password: 'Aa123456',
        name: undefined,
        sex: '1',
        mobile: undefined,
        email: undefined,
        birthday: undefined,
        org: null,
        role: null,
        description: undefined
      }
      this.$refs[formName].resetFields()
    },
    async getDepartment() {
      // 获取部门数据
      try {
        const data = await fetchTree({ groupType: '2' })
        addLevel(data)
        this.departmentList = data
      } catch (error) {
        console.log(error)
      }
    },
    async getRole() {
      // 获取角色数据
      try {
        const data = await fetchTree({ groupType: '1' })
        addLevel(data)
        this.roleList = data
      } catch (error) {
        console.log(error)
      }
    },
    departmentChanged(value) {
      // 部门改变时
      this.temp.org = value ? { id: value[value.length - 1], groupType: 2 } : null
    },
    roleChanged(value) {
      // 角色改变时
      this.temp.role = value ? { id: value[value.length - 1], groupType: 1 } : null
    }
  }
}
</script>
